package com.junqi.media.hls;

import com.junqi.common.entity.RoomLiveMq;
import com.junqi.media.config.ThreadPoolConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;

@Component
public class HlsHandler {
    /**
     * hls切片地址
     */
    @Value(value = "${jq.file_path}")
    private String filePath="";

    @Autowired
    @Qualifier(ThreadPoolConfig.MEDIA_EXECUTOR)
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;//线程池

    public static ConcurrentHashMap<String, HlsTask> taskMap = new ConcurrentHashMap<>();

    public void startHls(RoomLiveMq roomLiveMq){
        try {
            HlsTask hlsTask = new HlsTask(roomLiveMq.getRtmpUrl()+roomLiveMq.getRtmpCode(), filePath,roomLiveMq.getRoomId());
            Future<?> future = threadPoolTaskExecutor.submit(hlsTask);
            taskMap.put(roomLiveMq.getRoomId(),hlsTask);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 关闭hls切片
     * @param roomId
     */
    public void endHls(String roomId) {
        // 区分不同媒体
        HlsTask task = taskMap.get(roomId);
        if (task != null) {
            task.setRunning(false);
            taskMap.remove(taskMap);
        }
    }
}
